<?php
namespace app\admin\controller;
use \think\Db;
/**
 * 登录
 * @author xiegaolei
 *
 */
class Login extends \think\Controller
{	
    
	/**
	 * 登录页
	 */
    public function index(){
     
    	if(is_login()){
    		$this->redirect('index/index');
    	}
    	
    	return $this->fetch();
    	
    }
    
    /**
     * 登录验证
     */
    public function loginAuth(){
    	
    	if ($this->request->isPost()){
    		
    		//验证规则
    		$rule = [
    				'username'  => ['require','max'=>'25','alpha'],
    				'password'  => ['require'],
    				'verify' 	=> ['require','captcha'],
    				 
    		];
    		 
    		//提示信息
    		$msg = [
    				'username.require' => '账号必须',
    				'username.max'     => '账号最多不能超过25个字符',
    				'username.alpha'   => '账号必须是字母',
    				'password'   	   => '密码必须',
    				'verify.require'   => '验证码必须',
    				'verify.captcha'   => '验证码错误',
    		];
    		//接收数据
    		$data = [
    				'username'  => input('username','','trim'),
    				'password'   => input('password','','trim'),
    				'verify' => input('verify','','trim')
    		];
    		 
    		//验证输入数据合法性
    		$validate = new \think\Validate($rule, $msg);
    		$result   = $validate->check($data);
    		if (!$result){
    			$error = $validate->getError();
    			ajax_return_error($error);
    		}
    		
    		//账号验证
    		$uid = $this->logins($data['username'], $data['password']);
    		if(0 < $uid){ //登录成功
    		
    			ajax_return_ok(['url'=>url("index/index")] ,"登录成功！");
    		
    		} else { //登录失败
    			switch($uid) {
    				case -1: $error = '用户不存在或被禁用！'; break; //系统级别禁用
    				case -2: $error = '密码错误！'; break;
    				case -3: $error = '用户组不存在或被禁用！'; break;
    				default: $error = '未知错误！'; break; // 0-接口参数错误（调试阶段使用）
    			}
    			ajax_return_error($error);
    		}
    	}
    	
    	
    }
    
    
    
    /**
     * 用户登录认证
     * @param  string  $username 用户名
     * @param  string  $password 用户密码
     * @return integer           登录成功-用户ID，登录失败-错误编号
     */
    public function logins($username, $password){
    	 //用户
    	$admin = Db::name('admin')->where('username',$username)->find();
    	//角色
    	$role = Db::name('auth_group_access')
    			 ->alias('a')
    			 ->field('b.*')
    			 ->join('__AUTH_GROUP__ b','a.group_id = b.id')
    			 ->where('uid',$admin['id'])
    			 ->find();
    		
    	if (empty($role) || $role['status'] != 1) {
    		return -3;
    	}
    
    	if(is_array($admin) && $admin['isEnabled']){
    		/* 验证用户密码 */
    		if(encrypt_pass($password) === $admin['password']){
    			/* 记录登录SESSION */
    			$auth = array(
    					'uid'             => $admin['id'],
    					'username'        => $admin['username'],
    					'loginTime'		  => $admin['loginTime'],
    					'role'			  => $role['title'],
    					'roleId'		  => $role['id'],
    			);
    
    			session('admin_auth', $auth);
    			session('admin_auth_sign', data_auth_sign($auth));
    			$this->updateLogin($admin['id'],$admin['username'],$role['title']); //更新用户登录信息
    			return $admin['id']; //登录成功，返回用户ID
    		} else {
    			return -2; //密码错误
    		}
    	} else {
    		return -1; //用户不存在或被禁用
    	}
    }
    
    /**
     * 退出登录
     */
    public function logout(){
    	if(is_login()){
    		session('admin_auth', null);
    		session('admin_auth_sign', null);
    		session('[destroy]');
    		$this->redirect('login/index');
    	} else {
    		$this->redirect('login/index');
    	}
    }
    
    
    
    /**
     * 更新用户登录信息
     * @param  integer $uid 用户ID
     */
    protected function updateLogin($uid,$username,$role){
    	$data = array(
    			'loginTime'   => time(),
    			'loginIp'     => request()->ip(),
    	);
    	Db::name('admin')->where('id',$uid)->update($data);
    	
    	$data['uid'] = $uid;
    	$data['username'] = $username;
    	$data['roles'] = $role;
    	Db::name('login_log')->insert($data);
    	
    }
     
    
    
}
